//
//  UserInfoViewController.m
//  huashiedu
//
//  Created by oceans on 2018/8/31.
//  Copyright © 2018年 hema. All rights reserved.
//

#import "UserInfoViewController.h"
#import "UserInfoImageTableViewCell.h"
#import "ChangeUserNameViewController.h"
#import "SelectClassCategoryViewController.h"
#import "HttpRequest.h"
#import "TipManager.h"
#import <UIImageView+WebCache.h>

@interface UserInfoViewController () <UITableViewDelegate, UITableViewDataSource, UIImagePickerControllerDelegate, UINavigationControllerDelegate>

@property (strong, nonatomic) UITableView *tableview;
@property (strong, nonatomic) NSMutableArray *userTitleArr;
@property (strong, nonatomic) NSArray *teacherTitleArr;
@property (strong, nonatomic) UIView *dateView;
@property (strong, nonatomic) UIDatePicker *datePicker;
@end

@implementation UserInfoViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.userTitleArr = [NSMutableArray arrayWithArray:@[@"头像", @"昵称", @"姓名", @"性别", @"生日", @"婚姻状况", @"爱好分类"]];
    if ([UserModel shared].loginUser.marriage == 1) {
        [_userTitleArr insertObject:@"子女数目" atIndex:6];
    }
    self.teacherTitleArr = @[@"头像", @"昵称", @"姓名", @"性别", @"生日", @"民族", @"认证等级", @"教学分类"];
    [self setupView];
}

- (void)viewWillAppear:(BOOL)animated {
    
    [super viewWillAppear:animated];
    [self.tableview reloadData];
}

- (void)setupView {
    
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationItem.title = @"个人信息";
    
    self.tableview = [[UITableView alloc] initWithFrame:CGRectMake(0, XNavigationHeight, ScreenWidth, ScreenHeight - XNavigationHeight) style:UITableViewStyleGrouped];
    _tableview.delegate = self;
    _tableview.dataSource = self;
    _tableview.separatorInset = UIEdgeInsetsMake(0, 20, 0, 0);
    _tableview.backgroundColor = COLOR(245, 245, 245, 1);
    [_tableview registerNib:[UINib nibWithNibName:@"UserInfoImageTableViewCell" bundle:nil] forCellReuseIdentifier:@"UserInfoImageTableViewCell"];
    [self.view addSubview:_tableview];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    if ([UserModel shared].userType == 1) {
        return 8;
    }else if ([UserModel shared].userType == 3) {
        return 7;
    }
    return _userTitleArr.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.row == 0) {
        return 60.0;
    }
    return 55.0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.row == 0) {
        
        UserInfoImageTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"UserInfoImageTableViewCell"];
        cell.faceImageView.hidden = NO;
        cell.starView.hidden = YES;
        return cell;
    }else if (indexPath.row == 6) {
        
        if ([UserModel shared].userType == 0) {
            
            static NSString *identity = @"normalcell";
            UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identity];
            if (cell == nil) {
                cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:identity];
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
            }
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            return cell;
        }else {
            
            UserInfoImageTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"UserInfoImageTableViewCell"];
            cell.accessoryType = UITableViewCellAccessoryNone;
            cell.imageView.hidden = YES;
            cell.starView.hidden = NO;
            return cell;
        }
    }else {
        
        static NSString *identity = @"normalcell";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identity];
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:identity];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        if (indexPath.row > 1 && ([UserModel shared].userType != 0)) {
            cell.accessoryType = UITableViewCellAccessoryNone;
        }else {
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        }
        return cell;
    }
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.row == 0) {
        UserInfoImageTableViewCell *icell = (UserInfoImageTableViewCell *)cell;
        [icell.faceImageView sd_setImageWithURL:[NSURL URLWithString:[UserModel shared].loginUser.avatar]];
        icell.titleLabel.text = @"头像";
    }else {
        if ([UserModel shared].userType == 0) {
            cell.textLabel.text = _userTitleArr[indexPath.row];
        }else {
            cell.textLabel.text = _teacherTitleArr[indexPath.row];
        }
    }
    
    switch (indexPath.row) {
        case 1:
            cell.detailTextLabel.text = [UserModel shared].loginUser.nickname;
            break;
            
        case 2:
            cell.detailTextLabel.text = [UserModel shared].loginUser.realname;
            break;
            
        case 3:
            if ([UserModel shared].loginUser.gender == 1) {
                cell.detailTextLabel.text = @"男";
            }else if ([UserModel shared].loginUser.gender == 2) {
                cell.detailTextLabel.text = @"女";
            }else {
                cell.detailTextLabel.text = @"未知";
            }
            break;
            
        case 4:
            cell.detailTextLabel.text = [UserModel shared].loginUser.birthday;
            break;
        default:
            break;
    }
    
    
    if ([UserModel shared].userType == 0 && indexPath.row > 4) {
        
        if (indexPath.row == 5) {
            if ([UserModel shared].loginUser.marriage == 1) {
                cell.detailTextLabel.text = @"已婚";
            }else if ([UserModel shared].loginUser.marriage == 2) {
                cell.detailTextLabel.text = @"未婚";
            }else {
                cell.detailTextLabel.text = @"";
            }
        }else if (indexPath.row == 6) {
            
            if ([UserModel shared].loginUser.marriage == 1) {
                if ([UserModel shared].loginUser.children < 6) {
                    cell.detailTextLabel.text = [NSString stringWithFormat:@"%d个", [UserModel shared].loginUser.children];
                }else {
                    cell.detailTextLabel.text = @"5个及以上";
                }
            }else {
                cell.detailTextLabel.text = [UserModel shared].loginUser.hobyString;
            }
        }else {
            cell.detailTextLabel.text = [UserModel shared].loginUser.hobyString;
        }
    }else if([UserModel shared].userType != 0 && indexPath.row > 4) {
        
        if (indexPath.row == 5) {
            cell.detailTextLabel.text = [UserModel shared].loginUser.nation;
        }else if (indexPath.row == 6) {
            
            UserInfoImageTableViewCell *ucell = (UserInfoImageTableViewCell *)cell;
            ucell.starView.value = [UserModel shared].loginUser.grade;
            ucell.textLabel.text = nil;
            ucell.titleLabel.text = @"认证等级";
        }else if (indexPath.row == 7) {
            cell.detailTextLabel.text = [UserModel shared].loginUser.scopeString;
        }
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.row < 2) {
        if (indexPath.row == 0) {
            [self showImagePicker];
        }else {
            ChangeUserNameViewController *user = [[ChangeUserNameViewController alloc] init];
            user.type = 0;
            [self.navigationController pushViewController:user animated:YES];
        }
    }else if ([UserModel shared].userType == 0) {
        
        if (indexPath.row == 2) {
            ChangeUserNameViewController *user = [[ChangeUserNameViewController alloc] init];
            user.type = 1;
            [self.navigationController pushViewController:user animated:YES];
        }else if (indexPath.row == 3) {
            
            [self showGenderAlert];
        }else if (indexPath.row == 4) {
            
            self.dateView.hidden = NO;
        }else if (indexPath.row == 5) {
            
            [self showMarriedAlert];
        }else if (indexPath.row == 6) {
            
            if ([UserModel shared].loginUser.marriage == 1) {
                [self showChildrenNumAlert];
            }else {
                [self toSelectClassCategory];
            }
        }else if (indexPath.row == 7) {
            [self toSelectClassCategory];
        }
    }
}

- (void)toSelectClassCategory {
    
    SelectClassCategoryViewController *controller = [[SelectClassCategoryViewController alloc] init];
    [self.navigationController pushViewController:controller animated:YES];
}

- (UIView *)dateView {
    if (!_dateView) {
        
        _dateView = [[UIView alloc] initWithFrame:CGRectMake(0, ScreenHeight - 300, ScreenWidth, 300)];
        _dateView.backgroundColor = [UIColor whiteColor];
        [_dateView addSubview:self.datePicker];
        
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake(ScreenWidth - 60, 0, 50, 30);
        button.titleLabel.font = [UIFont systemFontOfSize:15.0];
        [button addTarget:self action:@selector(finishDate) forControlEvents:UIControlEventTouchUpInside];
        [button setTitleColor:COLOR(155, 155, 155, 1) forState:UIControlStateNormal];
        [button setTitle:@"完成" forState:UIControlStateNormal];
        [_dateView addSubview:button];
        
        [self.view addSubview:_dateView];
    }
    return _dateView;
}

- (UIDatePicker *)datePicker {
    
    if (!_datePicker) {
        
        _datePicker = [[UIDatePicker alloc] initWithFrame:CGRectMake(0, 30, ScreenWidth, 270)];
        [_datePicker setDatePickerMode:UIDatePickerModeDate];
        _datePicker.maximumDate = [NSDate date];
        _datePicker.locale = [NSLocale localeWithLocaleIdentifier:@"zh"];
    }
    return _datePicker;
}

- (void)finishDate {
    
    self.dateView.hidden = YES;
    NSDate *date = self.datePicker.date;
    NSDateFormatter *formate = [[NSDateFormatter alloc] init];
    [formate setDateFormat:@"yyyy-MM-dd"];
    NSString *dateString = [formate stringFromDate:date];
    
    __weak typeof(self) weakself = self;
    [[UserModel shared] updateUserinfo:@"birthday" value:dateString successBlock:^{
        [weakself.tableview reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:4 inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
    }];
}

- (void)showGenderAlert {
    
    UIAlertController *controller = [UIAlertController alertControllerWithTitle:nil message:@"请选择性别" preferredStyle:UIAlertControllerStyleAlert];
    __weak typeof(self) weakself = self;
    [controller addAction:[UIAlertAction actionWithTitle:@"男" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [weakself updateGenderInfo:1];
    }]];
    [controller addAction:[UIAlertAction actionWithTitle:@"女" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [weakself updateGenderInfo:2];
    }]];
    [controller addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
    [self presentViewController:controller animated:YES completion:nil];
}

- (void)showMarriedAlert {
    
    UIAlertController *controller = [UIAlertController alertControllerWithTitle:nil message:@"请选择婚姻状况" preferredStyle:UIAlertControllerStyleAlert];
    __weak typeof(self) weakself = self;
    [controller addAction:[UIAlertAction actionWithTitle:@"已婚" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [weakself updateMarrie:1];
    }]];
    [controller addAction:[UIAlertAction actionWithTitle:@"未婚" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [weakself updateMarrie:2];
    }]];
    [controller addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
    [self presentViewController:controller animated:YES completion:nil];
}

- (void)childrenNumberTitle:(BOOL)show {
    
    if (show) {
        if ([_userTitleArr containsObject:@"子女数目"]) {
            return;
        }
        [self.userTitleArr insertObject:@"子女数目" atIndex:6];
    }else {
        [_userTitleArr removeObject:@"子女数目"];
    }
    [self.tableview reloadData];
}

- (void)showChildrenNumAlert {
    
    __weak typeof(self) weakself = self;
    UIAlertController *controller = [UIAlertController alertControllerWithTitle:nil message:@"请选择孩子人数" preferredStyle:UIAlertControllerStyleAlert];
    [controller addAction:[UIAlertAction actionWithTitle:@"0" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [weakself updateChildrenInfo:0];
    }]];
    [controller addAction:[UIAlertAction actionWithTitle:@"1" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [weakself updateChildrenInfo:1];
    }]];
    [controller addAction:[UIAlertAction actionWithTitle:@"2" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [weakself updateChildrenInfo:2];
    }]];
    [controller addAction:[UIAlertAction actionWithTitle:@"3" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [weakself updateChildrenInfo:3];
    }]];
    [controller addAction:[UIAlertAction actionWithTitle:@"4" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [weakself updateChildrenInfo:4];
    }]];
    [controller addAction:[UIAlertAction actionWithTitle:@"5" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [weakself updateChildrenInfo:5];
    }]];
    [controller addAction:[UIAlertAction actionWithTitle:@"5个以上" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [weakself updateChildrenInfo:6];
    }]];
    [controller addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
    [self presentViewController:controller animated:YES completion:nil];
}

- (void)showImagePicker {
    
    
    UIAlertController *controller = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    __weak typeof(self) weakself = self;
    [controller addAction:[UIAlertAction actionWithTitle:@"打开相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [weakself createImagePicker:UIImagePickerControllerSourceTypePhotoLibrary];
    }]];
    [controller addAction:[UIAlertAction actionWithTitle:@"拍照上传" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [weakself createImagePicker:UIImagePickerControllerSourceTypeCamera];
    }]];
    [controller addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
    [self presentViewController:controller animated:YES completion:nil];
}

- (void)createImagePicker:(UIImagePickerControllerSourceType)sourceType {
    
    UIImagePickerController *controller = [[UIImagePickerController alloc] init];
    controller.sourceType = sourceType;
    controller.delegate = self;
    controller.allowsEditing = YES;
    [self presentViewController:controller animated:YES completion:nil];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [picker dismissViewControllerAnimated:YES completion:nil];
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
    
    [picker dismissViewControllerAnimated:YES completion:nil];
    UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage];
    NSData *data = UIImageJPEGRepresentation(image, 0.1);
    __weak typeof(self) weakself = self;
    [HttpRequest uploadImage:kupload_image paras:@{@"scope": @"user"} image:data showProgress:NO successful:^(id  _Nullable result) {
        
        [weakself updateImageInfo:[result objectForKey:@"data"]];
    } failed:^(int code, NSString *errMsg) {
        
    }];
}

- (void)updateImageInfo:(NSDictionary *)data {
    
    __weak typeof(self) weakself = self;
    [[UserModel shared] updateUserinfo:@"avatar" value:data[@"path"] successBlock:^{
        [TipManager showTip:@"修改成功"];
        
        [weakself.tableview reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:0 inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
    }];
}

/**1 男， 2女*/
- (void)updateGenderInfo:(int)gender {
    
    __weak typeof(self) weakself = self;
    [[UserModel shared] updateUserinfo:@"gender" value:[NSNumber numberWithInt:gender] successBlock:^{
        [weakself.tableview reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:3 inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
    }];
}

/**已婚：1，未婚：2*/
- (void)updateMarrie:(int)marriage {
    
    __weak typeof(self) weakself = self;
    [[UserModel shared] updateUserinfo:@"marriage" value:[NSNumber numberWithInt:marriage] successBlock:^{
        if (marriage == 1) {
            [weakself childrenNumberTitle:YES];
        }else {
            [weakself childrenNumberTitle:NO];
        }
    }];
}

/**0-6, 6是5个及以上*/
- (void)updateChildrenInfo:(int)children {
    
    if ([UserModel shared].loginUser.children == children) {
        return;
    }
    __weak typeof(self) weakself = self;
    [[UserModel shared] updateUserinfo:@"children" value:[NSNumber numberWithInt:children] successBlock:^{
        [weakself.tableview reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:6 inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
